<template>
  <div class="container">
    <div class="box">
      <h1>
        <div class="login-logo">
          <!-- <img src="/favicon.ico"> -->
        </div>
        <div>{{ $t(systemTitle) }}</div>
      </h1>
      <el-form class="form">
        <el-input
          size="large"
          v-model="form.name"
          :placeholder="$t('message.system.userName')"
          type="text"
          maxlength="50"
        >
          <template #prepend>
            <i class="sfont system-xingmingyonghumingnicheng"></i>
          </template>
        </el-input>
        <el-input
          size="large"
          ref="password"
          v-model="form.password"
          :type="passwordType"
          :placeholder="$t('message.system.password')"
          name="password"
          maxlength="50"
          @keyup.enter="submit"
        >
          <template #prepend>
            <i class="sfont system-mima"></i>
          </template>
          <template #append>
            <i
              class="sfont password-icon"
              :class="passwordType ? 'system-yanjing-guan': 'system-yanjing'"
              @click="passwordTypeChange"
            ></i>
          </template>
        </el-input>
        <div class="remember-password">
          <el-checkbox v-model="rememberPwd" label="记住密码" />
        </div>
        <el-button
          type="primary"
          :loading="form.loading"
          @click="submit"
          style="width: 100%;"
          size="large"
        >{{ $t('message.system.login') }}</el-button>
      </el-form>
      <div class="fixed-top-right">
        <!-- <select-lang /> -->
        <!-- <i class="fa fa-camera-retro"></i> -->
      </div>
    </div>
    <!--<Earth></Earth>-->
  </div>
</template>

<script lang="ts">
import md5 from 'js-md5';
import jwt from 'jsonwebtoken';
import { Base64 } from 'js-base64';
import { encode, decode } from 'js-base64';
import { systemTitle } from '@/config'
import { defineComponent, ref, reactive } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import type { RouteLocationRaw } from 'vue-router'
import { addRoutes } from '@/router'
import { ElMessage } from 'element-plus'
import selectLang from '@/layout/Header/functionList/word.vue'
import { getAdminInfo } from '@/api/service/user'


import Earth from '@/components/backgroundComp/earth.vue'

export default defineComponent({
  components: {
    selectLang,
    Earth
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const form = reactive({
      name: '',
      password: '',
      loading: false
    })
    const rememberPwd = ref(false) // 记住密码
    // 记住密码
    setTimeout(() => {
      if (localStorage.getItem('rinfo')) {
        const rInfo = JSON.parse(Base64.decode(localStorage.getItem('rinfo')))
        rememberPwd.value = rInfo.rememberPwd
        form.name = rInfo.name
        form.password = rInfo.password
      } else {
        rememberPwd.value = false
        form.name = ''
        form.password = ''
      }
    }, 1000);
    
    const passwordType = ref('password')
    const passwordTypeChange = () => {
      passwordType.value === '' ? passwordType.value = 'password' : passwordType.value = ''
    }
    const checkForm = () => {
      return new Promise((resolve, reject) => {
        if (form.name === '') {
          ElMessage.warning({
            message: '用户名不能为空',
            type: 'warning'
          });
          return;
        }
        if (form.password === '') {
          ElMessage.warning({
            message: '密码不能为空',
            type: 'warning'
          })
          return;
        }
        resolve(true)
      })
    }
    // 获取登录信息
    const getAdminInfoFun = () => {
      return new Promise((resolve, reject) => {
        getAdminInfo().then((res: any) => {
          if (res.code === 200) {
            store.commit('user/adminInfoChange', res.data)
            resolve(true)
          }
        }).catch(() => {
          reject(false)
        })
      })
      
    }
    const submit = () => {
      // checkForm()
      // .then(() => {
      //   form.loading = true
      //   let data = {
      //     user_name: form.name,
      //     pass_word: form.password
      //   }
      //   store.dispatch('user/login', data)
      //   .then(async () => {
      //     ElMessage.success({
      //       message: '登录成功',
      //       type: 'success',
      //       showClose: true,
      //       duration: 1000
      //     })
      //     await addRoutes()
      //     await router.push(route.query.redirect as RouteLocationRaw || '/')
      //   }).finally(() => {
      //     form.loading = false
      //   })
      // })
      checkForm()
      .then(() => {
        form.loading = true
        let data = {
          user_name: form.name,
          pass_word: md5(form.password) // .toUpperCase()
        }
        store.dispatch('user/whaleYunLoginAction', data)
        .then(async (result) => {
          // 存贮用户信息及token
          let res = result.token
          let base64Info = res.split('.')[1];
          let info = Base64.decode(base64Info);
          localStorage.setItem('LoginInfo', info)
          localStorage.setItem('Authorization', res)

          // 获取登录信息及权限
          await getAdminInfoFun()

          ElMessage.success({
            message: '登录成功',
            type: 'success',
            showClose: true,
            duration: 1000
          })

          // 如果用户勾选记住密码
          if (rememberPwd.value) {
            let rinfo: any = {
              name: form.name,
              password: form.password,
              rememberPwd: true
            }
            rinfo = JSON.stringify(rinfo)
            let encodeInfo = Base64.encode(rinfo)
            localStorage.setItem('rinfo', encodeInfo)
          } else {
            localStorage.setItem('rinfo', '')
          }
          

          await addRoutes()
          await router.replace(route.query.redirect as RouteLocationRaw || '/')
        }).catch((e) => {
          // if (e.code != 200) {
          //   ElMessage.error(e.message)
          // }
        })
        .finally(() => {
          form.loading = false
        })
      })
    }
    return {
      systemTitle,
      form,
      rememberPwd,
      passwordType,
      passwordTypeChange,
      submit,
      getAdminInfoFun
    }
  }
})
</script>

<style lang="scss" scoped>
.container {
  position: relative;
  width: 100vw;
  height: 100vh;
  background-color: #eef0f3;
  background: url('/images/login-bg.png');
  background-size: 100% 100%;
  .login-logo{
    margin-bottom: 10px;
    img{
      height: 80px;
    }
  }
  .box {
    width: 500px;
    position: absolute;
    left: 50%;
    top: 50%;
    background: rgba(255, 255, 255, .95);
    // background: rgba(0, 0, 0, 0.3);
    border-radius: 8px;
    transform: translate(-50%, -50%);
    // height: 489px;
    overflow: hidden;
    // box-shadow: 0 6px 20px 5px rgba(152, 152, 152, 0.1),
    //   0 16px 24px 2px rgba(117, 117, 117, 0.14);
    box-shadow: 0 10px 30px #666;
    z-index: 2;
    padding: 80px 0;
    h1 {
      // margin-top: 80px;
      text-align: center;
      color: #000;
    }
    .form {
      width: 80%;
      margin: 40px auto 15px;
      .el-input {
        margin-bottom: 20px;
      }
      .password-icon {
        cursor: pointer;
        color: #409eff;
      }
      .remember-password{
        text-align: left;
        margin-bottom: 20px;
      }
    }
    .fixed-top-right {
      position: absolute;
      top: 10px;
      right: 10px;
    }
  }
}
@media screen and (max-width: 750px) {
  .container .box {
    width: 100vw;
    height: 100vh;
    box-shadow: none;
    left: 0;
    top: 0;
    transform: none;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    h1 {
      margin-top: 0;
    }
    .form {
    }
  }
}
</style>
